package com.cuitrip.business.setting;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.MainApplication;
import com.cuitrip.app.base.UnitUtils;
import com.cuitrip.business.bill.Rate;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.ModifyPasswdActivity;
import com.cuitrip.business.share.ShareChannelBuilder;
import com.cuitrip.business.share.ui.ShareDialogFragment;
import com.cuitrip.business.tripservice.proxy.PriceProxy;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.webview.H5UrlMaker;
import com.cuitrip.business.webview.proxy.WebViewProxy;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.image.process.MakeImageUtil;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ToastUtil;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created on 7/16.
 */
public class SettingActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static final String HAS_PASSWORD = "hasPasswd";

    public static final String MARKET_URL = "market://details?id=";

    public static final String INTERNATIONAL_MARKET = "http://market.android.com/details?id=";

    @Bind(R.id.currency_layout)
    ItemLayout currencyLayout;
    //    private ShareUtil mShareUtil;
    private ApiProxy mApiProxy = new ApiProxy(this);
    private boolean hasPasswd;
    private ShareDialogFragment shareDialogFragment;

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.setting);
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.ct_setting);
        ItemLayout modifyPwdLayout = (ItemLayout) findViewById(R.id.modify_pwd_layout);
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo != null) {
            modifyPwdLayout.setVisibility(View.VISIBLE);
            modifyPwdLayout.setleftText(userInfo.isHasPasswrd() ? getString(R.string.password_change) : getString(R.string.sign_up_set_password));
        } else {
            modifyPwdLayout.setVisibility(View.GONE);
        }
        findViewById(R.id.logout).setVisibility(LoginInstance.isLogin() ? View.VISIBLE : View.GONE);
        if (LoginInstance.isLogin()) {
            hasPasswd = LoginInstance.getInstance().getUserInfo().isHasPasswrd();
        }

    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
    }

    public void initData() {
        currencyLayout.setmRightText(UnitUtils.getSettingMoneyType().toUpperCase());
    }

    private void showCurrencySelect(List<Rate> rateList) {
        PriceProxy.getInstance().showCurrencySelect(this, rateList, new PriceProxy.CurrencyCallback() {
            @Override
            public void onCurrencySelect(String currency) {
                UnitUtils.setSettingMoneyType(currency);
                currencyLayout.setmRightText(currency);
            }
        });
    }

    @OnClick(R.id.currency_layout)
    protected void selectCurrencyLayout() {
        showNoCancelDialog();
        OrderBusiness.getRates(mApiProxy, 0, 20);
    }

    @OnClick(R.id.modify_pwd_layout)
    protected void modifyPwd() {
        TrackUtil.trackScreenName("/user/change_password");
        startActivity(new Intent(this, ModifyPasswdActivity.class).putExtra(HAS_PASSWORD, hasPasswd));
    }

    @OnClick(R.id.about_layout)
    protected void about() {
        TrackUtil.trackScreenName("/settings/about");
        startActivity(new Intent(this, AboutActivity.class));
    }

    @OnClick(R.id.suggest_layout)
    protected void suggest() {
        TrackUtil.trackScreenName("/settings/feedback");
        startActivity(new Intent(this, SuggestActivity.class));
    }

    @OnClick(R.id.invite_layout)
    public void share() {
        if (shareDialogFragment != null && shareDialogFragment.isShowing()) {
            return;
        }

        shareDialogFragment = ShareDialogFragment.newInstance(ShareChannelBuilder.TripShareChannel.INVITE_TYPE, MakeImageUtil.takeScreenShot(this));
        showDialogFragment(shareDialogFragment);
    }

    @OnClick(R.id.vote_layout)
    protected void vote() {
        String url = MARKET_URL + this.getPackageName();
        Intent installIntent = new Intent("android.intent.action.VIEW");
        installIntent.setData(Uri.parse(url));
        Jumper.launchActivity(this, installIntent);
    }

    @OnClick(R.id.help_layout)
    protected void help() {
        TrackUtil.trackScreenName("/settings/help");
        WebViewProxy.getInstance().browseWeb(this, H5UrlMaker.getHelpUrl());
    }

    @OnClick(R.id.contact_layout)
    protected void contact() {
        TrackUtil.trackScreenName("/settings/contact");
        startActivity(new Intent(this, RelationActivity.class));
    }

    @OnClick(R.id.logout)
    protected void logout() {
        showNoCancelDialog();
        UserBusiness.logout(mApiProxy);
    }


    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.LOGOUT.equals(response.getApiName())) {
            hideNoCancelDialog();
            MainApplication.getInstance().logOut(false);
        } else if (ApiManager.GET_RATES.equals(response.getApiName())) {
            hideNoCancelDialog();
            if (response.isResponseNormal() && response.result instanceof List) {
                List<Rate> rateList = (List<Rate>) response.result;
                boolean hasUSD = false;
                for (int i = 0; i < rateList.size(); i++) {
                    Rate rate = rateList.get(i);
                    if ("USD".equalsIgnoreCase(rate.currency)) {
                        hasUSD = true;
                    }
                }
                if (!hasUSD) {
                    Rate usd = new Rate("", "", "USD");
                    rateList.add(0, usd);
                }
                showCurrencySelect(rateList);
            } else {
                if (TextUtils.isEmpty(response.msg)) {
                    ToastUtil.toast(response.msg);
                }

            }

        }
        return false;
    }


}
